<template>
    <div class="table-advanced-demo">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>表格高级功能演示</span>
                    <div class="feature-toggles">
                        <!-- 功能开关 -->
                        <el-switch
                            v-model="features.batchOperation"
                            active-text="批量操作"
                            :style="{marginRight: '10px'}"
                            @change="toggleFeature('batchOperation')"
                        />
                        <el-switch
                            v-model="features.contextMenu"
                            active-text="右键菜单"
                            :style="{marginRight: '10px'}"
                            @change="toggleFeature('contextMenu')"
                        />
                        <el-switch
                            v-model="features.columnWidthMemory"
                            active-text="列宽记忆"
                            :style="{marginRight: '10px'}"
                            @change="toggleFeature('columnWidthMemory')"
                        />
                        <el-switch
                            v-model="features.columnDrag"
                            active-text="列拖拽排序"
                            :style="{marginRight: '10px'}"
                            @change="toggleFeature('columnDrag')"
                        />
                        <el-button size="small" type="primary" @click="resetTable">重置表格设置</el-button>
                    </div>
                </div>
            </template>
            
            <!-- 操作指南 -->
            <el-alert
                v-if="activeFeatures.length > 0"
                type="info"
                :closable="false"
                :title="`当前启用的功能: ${activeFeatures.join(', ')}`"
                description="可以通过上方的开关切换不同功能，体验表格的高级交互功能"
            />
            <el-alert
                v-if="features.batchOperation"
                type="success"
                :closable="false"
                title="批量操作：选中多行数据后，顶部会出现批量操作工具栏"
                style="margin-top: 10px;"
            />
            <el-alert
                v-if="features.contextMenu"
                type="success"
                :closable="false"
                title="右键菜单：在表格行上右键点击，会出现上下文菜单"
                style="margin-top: 10px;"
            />
            <el-alert
                v-if="features.columnWidthMemory"
                type="success"
                :closable="false"
                title="列宽记忆：调整列宽后，刷新页面或重新进入，列宽会保持上次设置"
                style="margin-top: 10px;"
            />
            <el-alert
                v-if="features.columnDrag"
                type="success"
                :closable="false"
                title="列拖拽排序：可以拖拽表头调整列的顺序"
                style="margin-top: 10px;"
            />            <!-- 表格组件 -->            <Table 
                ref="tableRef"
                class="advanced-table"
                :column="tableColumn"
                :data="tableData"
                v-model:showComSearch="showAdvancedSearchValue"
                :selectionEnabled="features.batchOperation"
                :contextMenuEnabled="features.contextMenu"
                :tableId="'advanced-demo-table'"
                :draggable="draggableConfig"
                style="margin-top: 20px;"
                @selection-change="handleSelectionChange"
                @context-menu-click="handleContextMenuClick"
                @row-drag-end="handleRowDragEnd"
                @column-drag-end="handleColumnDragEnd">
                
                <!-- 自定义插槽：操作列 -->
                <template #operation="scope">
                    <el-button type="primary" size="small" @click="viewDetail(scope.data.row)">查看</el-button>
                    <el-button type="success" size="small" @click="editRow(scope.data.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteRow(scope.data.row)">删除</el-button>
                </template>
                
                <!-- 批量操作按钮 -->
                <template #batchActions="{ selection }">
                    <el-button type="primary" size="small" @click="batchExport(selection)">批量导出</el-button>
                    <el-button type="success" size="small" @click="batchEdit(selection)">批量编辑</el-button>
                    <el-button type="danger" size="small" @click="batchDelete(selection)">批量删除</el-button>
                </template>
            </Table>
            
            <!-- 表格操作结果展示区域 -->
            <div class="operation-log" v-if="operationLogs.length > 0">
                <h3>操作日志：</h3>
                <el-timeline>
                    <el-timeline-item
                        v-for="(log, index) in operationLogs"
                        :key="index"
                        :timestamp="log.time"
                        :type="log.type">
                        {{ log.message }}
                    </el-timeline-item>
                </el-timeline>
                <div class="log-actions">
                    <el-button size="small" type="info" @click="operationLogs = []">清空日志</el-button>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive, nextTick } from 'vue'
import Table from '/@/components/table/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格引用
const tableRef = ref<any>(null)

// 控制高级表格搜索显示
const showAdvancedSearchValue = ref(false)

// 功能开关状态
const features = reactive({
    batchOperation: true,      // 批量操作
    contextMenu: true,         // 右键菜单
    columnWidthMemory: true,   // 列宽记忆
    columnDrag: true           // 列拖拽排序
})

// 当前启用的功能名称列表
const activeFeatures = computed(() => {
    const result: string[] = []
    if (features.batchOperation) result.push('批量操作')
    if (features.contextMenu) result.push('右键菜单')
    if (features.columnWidthMemory) result.push('列宽记忆')
    if (features.columnDrag) result.push('列拖拽排序')
    return result
})

// 操作日志
const operationLogs = ref<{ message: string, time: string, type: 'primary' | 'success' | 'warning' | 'danger' | 'info' }[]>([])

// 添加操作日志
const addLog = (message: string, type: 'primary' | 'success' | 'warning' | 'danger' | 'info' = 'info') => {
    const now = new Date()
    const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`
    operationLogs.value.unshift({ message, time, type })
    
    // 最多保留20条日志
    if (operationLogs.value.length > 20) {
        operationLogs.value = operationLogs.value.slice(0, 20)
    }
}

// 表格列定义
const tableColumn = ref([
    { prop: 'id', label: 'ID', width: 80 },
    { prop: 'name', label: '姓名', width: 120 },
    { prop: 'age', label: '年龄', width: 80 },
    { prop: 'email', label: '邮箱', minWidth: 200 },
    { prop: 'address', label: '地址', minWidth: 250 },
    { prop: 'status', label: '状态', width: 100 },
    { prop: 'createTime', label: '创建时间', width: 180 },
    { prop: 'operation', label: '操作', width: 220, slotName: 'operation' }
])

// 生成模拟数据
const generateTableData = () => {
    const data = []
    const statuses = ['活跃', '禁用', '待审核']
    const addresses = [
        '北京市朝阳区', '上海市浦东新区', '广州市天河区', '深圳市南山区',
        '杭州市西湖区', '南京市鼓楼区', '武汉市武昌区', '成都市锦江区'
    ]
    
    for (let i = 1; i <= 20; i++) {
        data.push({
            id: i,
            name: `用户${i}`,
            age: Math.floor(Math.random() * 40) + 18,
            email: `user${i}@example.com`,
            address: addresses[Math.floor(Math.random() * addresses.length)] + `第${Math.floor(Math.random() * 100) + 1}号`,
            status: statuses[Math.floor(Math.random() * statuses.length)],
            createTime: new Date(Date.now() - Math.floor(Math.random() * 90) * 24 * 60 * 60 * 1000).toLocaleString()
        })
    }
    
    return data
}

// 表格数据
const tableData = ref(generateTableData())

// 当前选中行
const selectedRows = ref<any[]>([])

// 处理选择变化
const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows
    if (rows.length > 0) {
        addLog(`选中了 ${rows.length} 条数据`, 'primary')
    }
}

// 重置表格设置
const resetTable = async () => {
    try {
        await ElMessageBox.confirm('确定要重置表格设置吗？这将清除列宽和列顺序的记忆。', '确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        if (tableRef.value && tableRef.value.baTable) {
            // 重置列宽
            tableRef.value.baTable.resetColumnWidths()
            
            // 刷新表格布局
            setTimeout(() => {
                tableRef.value.refreshLayout()
                ElMessage.success('表格设置已重置')
                addLog('重置了表格设置', 'success')
            }, 100)
        }
    } catch {
        // 用户取消了操作
    }
}

// 切换功能
const toggleFeature = (feature: string) => {
    if (feature === 'columnDrag' && tableRef.value) {
        // 更新拖拽配置        Object.assign(draggableConfig, {
            column: features.columnDrag,
            row: features.columnDrag
        })
        
        console.log('拖拽配置已更新:', draggableConfig)
        
        // 启用或禁用列拖拽排序
        nextTick(() => {
            // 等待DOM更新后再更新拖拽实例
            if (tableRef.value) {
                tableRef.value.toggleColumnDrag(features.columnDrag)
                tableRef.value.toggleRowDrag(features.columnDrag)
                
                console.log('拖拽实例已更新')
            }
            
            if (features.columnDrag) {
                addLog('启用了拖拽排序功能', 'success')
            } else {
                addLog('禁用了拖拽排序功能', 'info')
            }
        })
    } else if (feature === 'columnWidthMemory' && tableRef.value && tableRef.value.baTable) {
        // 启用或禁用列宽记忆
        tableRef.value.baTable.rememberColumnWidth = features.columnWidthMemory
        
        if (features.columnWidthMemory) {
            addLog('启用了列宽记忆功能', 'success')
        } else {
            addLog('禁用了列宽记忆功能', 'info')
        }
    }
}

// 创建拖拽配置
const draggableConfig = reactive({
    row: true,
    column: true
})

// 初始化拖拽状态
console.log('初始化拖拽配置:', draggableConfig)

// 初始化表格功能
onMounted(() => {
    nextTick(() => {
        if (tableRef.value) {
            // 启用列拖拽排序
            tableRef.value.toggleColumnDrag(features.columnDrag)
            // 启用行拖拽排序
            tableRef.value.toggleRowDrag(features.columnDrag)
        }
        
        // 添加初始化日志
        addLog('表格组件已初始化，启用了高级功能演示', 'success')
    })
})

// 右键菜单点击处理
const handleContextMenuClick = (data: any) => {
    const { item, row } = data
    
    switch (item.rowAction) {
        case 'view':
            addLog(`通过右键菜单查看了用户: ${row.name}`, 'primary')
            ElMessage.info(`查看用户: ${row.name}`)
            break
        case 'edit':
            addLog(`通过右键菜单编辑了用户: ${row.name}`, 'success')
            ElMessage.success(`编辑用户: ${row.name}`)
            break
        case 'delete':
            addLog(`通过右键菜单删除了用户: ${row.name}`, 'danger')
            ElMessage.warning(`删除用户: ${row.name}`)
            break
    }
}

// 行操作按钮处理
const viewDetail = (row: any) => {
    addLog(`通过按钮查看了用户: ${row.name}`, 'primary')
    ElMessage.info(`查看用户详情: ${row.name}`)
}

const editRow = (row: any) => {
    addLog(`通过按钮编辑了用户: ${row.name}`, 'success')
    ElMessage.success(`编辑用户: ${row.name}`)
}

const deleteRow = (row: any) => {
    ElMessageBox.confirm(`确认删除用户 ${row.name}？`, '确认操作', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        addLog(`通过按钮删除了用户: ${row.name}`, 'danger')
        ElMessage.success(`已删除用户: ${row.name}`)
    }).catch(() => {})
}

// 批量操作处理
const batchExport = (selection: any[]) => {
    const names = selection.map(item => item.name).join(', ')
    addLog(`批量导出了 ${selection.length} 位用户数据: ${names}`, 'primary')
    ElMessage.info(`已导出 ${selection.length} 位用户数据`)
}

const batchEdit = (selection: any[]) => {
    const names = selection.map(item => item.name).join(', ')
    addLog(`批量编辑了 ${selection.length} 位用户: ${names}`, 'success')
    ElMessage.success(`批量编辑 ${selection.length} 位用户`)
}

const batchDelete = (selection: any[]) => {
    ElMessageBox.confirm(`确认删除选中的 ${selection.length} 位用户？`, '批量删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const names = selection.map(item => item.name).join(', ')
        addLog(`批量删除了 ${selection.length} 位用户: ${names}`, 'danger')
        ElMessage.success(`已删除 ${selection.length} 位用户`)
    }).catch(() => {})
}

// 处理行拖拽结束事件
const handleRowDragEnd = (event: { oldIndex: number, newIndex: number, data: any[] }) => {
    // 更新表格数据
    tableData.value = event.data
    
    addLog(`行拖拽: 将第 ${event.oldIndex + 1} 行移动到第 ${event.newIndex + 1} 行`, 'primary')
    ElMessage.success(`已将第 ${event.oldIndex + 1} 行移动到第 ${event.newIndex + 1} 行`)
}

// 处理列拖拽结束事件
const handleColumnDragEnd = (event: { oldIndex: number, newIndex: number, columns: any[] }) => {
    // 更新列定义
    tableColumn.value = event.columns
    
    const oldColumn = event.columns[event.newIndex]
    addLog(`列拖拽: 将 ${oldColumn.label || oldColumn.prop} 列移动到第 ${event.newIndex + 1} 位`, 'primary')
    ElMessage.success(`已调整列顺序`)
}
</script>

<style scoped lang="scss">
.table-advanced-demo {
    padding: 20px;
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .feature-toggles {
        display: flex;
        align-items: center;
    }
    
    .advanced-table {
        margin-bottom: 20px;
    }
    
    .operation-log {
        margin-top: 30px;
        border-top: 1px solid #eee;
        padding-top: 20px;
        
        h3 {
            margin-top: 0;
            margin-bottom: 15px;
            font-size: 16px;
            color: #333;
        }
        
        .log-actions {
            margin-top: 15px;
            text-align: right;
        }
    }
}
</style>